import React, { useEffect, useState } from 'react';
import { Card, Avatar, Descriptions, Button, Space, Statistic, Row, Col, Tabs, message, Spin, Empty } from 'antd';
import { UserOutlined, BookOutlined, ClockCircleOutlined, StarOutlined } from '@ant-design/icons';
import { useAuthStore } from '../store';
import { useNavigate } from 'react-router-dom';
import { logoutWithCookie } from '../utils/auth';
import { 
  getUserStudySummary, 
  getUserStudyRecords, 
  getInProgressCourses, 
  getCompletedCourses 
} from '../api/divide/study/sdk.gen';
import type { StudyRecordDto, StudyStatisticsDto } from '../api/divide/study/types.gen';

const { TabPane } = Tabs;

const Profile: React.FC = () => {
  const { user, logout } = useAuthStore();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [studySummary, setStudySummary] = useState<StudyStatisticsDto | null>(null);
  const [studyRecords, setStudyRecords] = useState<StudyRecordDto[]>([]);
  const [inProgressCourses, setInProgressCourses] = useState<StudyRecordDto[]>([]);
  const [completedCourses, setCompletedCourses] = useState<StudyRecordDto[]>([]);

  const userInfo = {
    username: user?.username || '用户',
    email: user?.email || '未设置邮箱',
    avatar: user?.avatar || '',
    joinDate: user?.createTime ? new Date(user.createTime).toLocaleDateString('zh-CN') : '未知',
  };

  // 获取学习数据
  const fetchStudyData = async () => {
    try {
      setLoading(true);
      
      // 获取学习统计
      const summaryResponse = await getUserStudySummary();
      if (summaryResponse.data?.code === 200 && summaryResponse.data.data) {
        setStudySummary(summaryResponse.data.data);
      }

      // 获取所有学习记录
      const recordsResponse = await getUserStudyRecords({
        query: { userId: user?.id || 0, page: 1, size: 100 }
      });
      if (recordsResponse.data?.code === 200 && recordsResponse.data.data?.records) {
        setStudyRecords(recordsResponse.data.data.records);
      }

      // 获取进行中的课程
      const inProgressResponse = await getInProgressCourses({
        query: { userId: user?.id || 0 }
      });
      if (inProgressResponse.data?.code === 200 && inProgressResponse.data.data) {
        setInProgressCourses(inProgressResponse.data.data);
      }

      // 获取已完成的课程
      const completedResponse = await getCompletedCourses({
        query: { userId: user?.id || 0 }
      });
      if (completedResponse.data?.code === 200 && completedResponse.data.data) {
        setCompletedCourses(completedResponse.data.data);
      }

    } catch (error) {
      console.error('获取学习数据失败:', error);
      message.error('获取学习数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user?.id) {
      fetchStudyData();
    }
  }, [user?.id]);

  const handleLogout = async () => {
    try {
      await logoutWithCookie();
      message.success('已成功退出登录');
      navigate('/login');
    } catch (error) {
      message.error('退出登录失败，请重试');
    }
  };

  // 计算统计数据
  const totalCourses = studyRecords.length;
  const completedCount = completedCourses.length;
  const inProgressCount = inProgressCourses.length;
  const completionRate = totalCourses > 0 ? Math.round((completedCount / totalCourses) * 100) : 0;

  return (
    <div style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <Spin spinning={loading}>
        <Row gutter={[24, 24]}>
          {/* 用户信息卡片 */}
          <Col xs={24} lg={8}>
            <Card>
              <div style={{ textAlign: 'center', marginBottom: 24 }}>
                <Avatar 
                  size={80} 
                  icon={<UserOutlined />} 
                  src={userInfo.avatar}
                  style={{ backgroundColor: '#1890ff' }}
                />
                <h2 style={{ margin: '16px 0 8px' }}>{userInfo.username}</h2>
                <p style={{ color: '#666', marginBottom: 16 }}>{userInfo.email}</p>
                <Space>
                  <Button type="primary" size="small">编辑资料</Button>
                  <Button size="small" onClick={handleLogout}>退出登录</Button>
                </Space>
              </div>
              <Descriptions column={1} size="small">
                <Descriptions.Item label="注册时间">{userInfo.joinDate}</Descriptions.Item>
                <Descriptions.Item label="学习时长">
                  {studySummary?.formattedTotalStudyDuration || '0小时'}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 学习统计 */}
            <Card style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={12}>
                  <Statistic 
                    title="总课程" 
                    value={totalCourses} 
                    prefix={<BookOutlined />} 
                  />
                </Col>
                <Col span={12}>
                  <Statistic 
                    title="已完成" 
                    value={completedCount} 
                    prefix={<ClockCircleOutlined />} 
                  />
                </Col>
              </Row>
              <Row gutter={16} style={{ marginTop: 16 }}>
                <Col span={12}>
                  <Statistic 
                    title="进行中" 
                    value={inProgressCount} 
                    prefix={<StarOutlined />} 
                  />
                </Col>
                <Col span={12}>
                  <Statistic 
                    title="完成率" 
                    value={completionRate} 
                    suffix="%"
                  />
                </Col>
              </Row>
            </Card>
          </Col>

          {/* 课程信息 */}
          <Col xs={24} lg={16}>
            <Card title="我的课程">
              <Tabs defaultActiveKey="all">
                <TabPane tab={`全部 (${totalCourses})`} key="all">
                  <Row gutter={[16, 16]}>
                    {studyRecords.map(course => (
                      <Col xs={24} key={course.id}>
                        <Card size="small">
                          <Row justify="space-between" align="middle">
                            <Col>
                              <h4 style={{ margin: 0 }}>{course.courseTitle}</h4>
                              <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                                进度: {course.progressPercent || 0}%
                              </p>
                              <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                                状态: {course.statusName || course.status}
                              </p>
                            </Col>
                            <Col>
                              <Button 
                                type="primary" 
                                size="small"
                                onClick={() => navigate(`/study/${course.courseId}`)}
                                disabled={course.status === '已完成'}
                              >
                                {course.status === '已完成' ? '已完成' : 
                                 course.status === '学习中' ? '继续学习' : '开始学习'}
                              </Button>
                            </Col>
                          </Row>
                          <div style={{ marginTop: 8 }}>
                            <div style={{ 
                              width: '100%', 
                              height: 4, 
                              backgroundColor: '#f0f0f0', 
                              borderRadius: 2 
                            }}>
                              <div style={{ 
                                width: `${course.progressPercent || 0}%`, 
                                height: '100%', 
                                backgroundColor: course.status === '已完成' ? '#52c41a' : '#1890ff', 
                                borderRadius: 2 
                              }} />
                            </div>
                          </div>
                        </Card>
                      </Col>
                    ))}
                    {studyRecords.length === 0 && (
                      <Col xs={24}>
                        <div style={{ textAlign: 'center', padding: '40px 0', color: '#666' }}>
                          <Empty description="暂无学习记录" />
                        </div>
                      </Col>
                    )}
                  </Row>
                </TabPane>
                
                <TabPane tab={`进行中 (${inProgressCount})`} key="in-progress">
                  <Row gutter={[16, 16]}>
                    {inProgressCourses.map(course => (
                      <Col xs={24} key={course.id}>
                        <Card size="small">
                          <Row justify="space-between" align="middle">
                            <Col>
                              <h4 style={{ margin: 0 }}>{course.courseTitle}</h4>
                              <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                                进度: {course.progressPercent || 0}%
                              </p>
                            </Col>
                            <Col>
                              <Button 
                                type="primary" 
                                size="small"
                                onClick={() => navigate(`/study/${course.courseId}`)}
                              >
                                继续学习
                              </Button>
                            </Col>
                          </Row>
                          <div style={{ marginTop: 8 }}>
                            <div style={{ 
                              width: '100%', 
                              height: 4, 
                              backgroundColor: '#f0f0f0', 
                              borderRadius: 2 
                            }}>
                              <div style={{ 
                                width: `${course.progressPercent || 0}%`, 
                                height: '100%', 
                                backgroundColor: '#1890ff', 
                                borderRadius: 2 
                              }} />
                            </div>
                          </div>
                        </Card>
                      </Col>
                    ))}
                    {inProgressCourses.length === 0 && (
                      <Col xs={24}>
                        <div style={{ textAlign: 'center', padding: '40px 0', color: '#666' }}>
                          <Empty description="暂无进行中的课程" />
                        </div>
                      </Col>
                    )}
                  </Row>
                </TabPane>
                
                <TabPane tab={`已完成 (${completedCount})`} key="completed">
                  <Row gutter={[16, 16]}>
                    {completedCourses.map(course => (
                      <Col xs={24} key={course.id}>
                        <Card size="small">
                          <Row justify="space-between" align="middle">
                            <Col>
                              <h4 style={{ margin: 0 }}>{course.courseTitle}</h4>
                              <p style={{ margin: 0, color: '#666', fontSize: 12 }}>
                                完成时间: {course.completionTime ? new Date(course.completionTime).toLocaleDateString('zh-CN') : '未知'}
                              </p>
                            </Col>
                            <Col>
                              <Button 
                                type="default" 
                                size="small"
                                disabled
                              >
                                已完成
                              </Button>
                            </Col>
                          </Row>
                          <div style={{ marginTop: 8 }}>
                            <div style={{ 
                              width: '100%', 
                              height: 4, 
                              backgroundColor: '#f0f0f0', 
                              borderRadius: 2 
                            }}>
                              <div style={{ 
                                width: '100%', 
                                height: '100%', 
                                backgroundColor: '#52c41a', 
                                borderRadius: 2 
                              }} />
                            </div>
                          </div>
                        </Card>
                      </Col>
                    ))}
                    {completedCourses.length === 0 && (
                      <Col xs={24}>
                        <div style={{ textAlign: 'center', padding: '40px 0', color: '#666' }}>
                          <Empty description="暂无已完成的课程" />
                        </div>
                      </Col>
                    )}
                  </Row>
                </TabPane>
              </Tabs>
            </Card>

            {/* 最近活动 */}
            <Card title="最近活动" style={{ marginTop: 16 }}>
              <div style={{ color: '#666', textAlign: 'center', padding: '40px 0' }}>
                <Empty description="暂无最近活动" />
              </div>
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default Profile;